package org.ham007.proxysender.server.twitter.follow;

import java.util.List;

import javax.jdo.PersistenceManager;

import org.ham007.proxysender.server.PMF;
import org.ham007.proxysender.server.twitter.MyTwitter;
import org.ham007.proxysender.server.twitter.entity.LastFollowInfo;

import twitter4j.IDs;
import twitter4j.Paging;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;

/**
 * フォロー状態一括変更処理
 * @author 223
 *
 */
public class AutoFollowProcesser {
	
	/**
	 * 全て読み直す
	 */
	private final int ALL_REREAD = 1;
	/**
	 * 1ページのメッセージ数
	 */
	private final int ONE_PAGE_COUNT = 10;
	//private final int MAX_USER_COUNT = 20;
	private Twitter twitter = null;
		
	/**
	 * フォロー状態の変更
	 * @param follow_enable フォロー状態
	 */
	public void followStateChange(boolean follow_enable)
	{
		try
		{	
			twitter = MyTwitter.get();
			callFriendship(follow_enable);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * 前回フォローユーザー情報の取得</br>
	 * 未取得時はnullを返す</br>
	 * </br>
	 * @return ユーザー情報
	 */
	private LastFollowInfo getLastFollowInfo()
	{
		LastFollowInfo last_follow = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try
		{
			last_follow = pm.getObjectById(LastFollowInfo.class, "follow");
		}
		catch(Exception e)
		{
			e.toString();
		}
		finally
		{
			if(last_follow != null)
				pm.close();
		}
		
		return last_follow;
	}
	
	/**
	 * 前回フォローユーザー情報の更新
	 * @param follow_info
	 */
	private void updateLastFollowInfo(LastFollowInfo follow_info)
	{
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		try
		{
			pm.makePersistent(follow_info);
		}
		finally
		{
			pm.close();
		}
	}
	
	private void callFriendship(boolean follow_enable) throws TwitterException
	{		
		IDs ids = twitter.getFollowersIDs();
		int id_length = ids.getIDs().length;
		int page_no = -1;
		LastFollowInfo last_follow = getLastFollowInfo();
		
		if(last_follow == null || last_follow.getLastUserId() == ALL_REREAD)
		{
			last_follow = new LastFollowInfo("follow", ids.getIDs()[id_length - 1]);
			page_no = (int)Math.ceil(id_length / (ONE_PAGE_COUNT * 1.0));
		}
		else if(last_follow.getLastUserId() == ids.getIDs()[0])
		{
			System.out.println("target user not found.");
			return;
		}
		else
		{
			for(int i=0;i<id_length;i++)
			{
				if(last_follow.getLastUserId() == ids.getIDs()[i])
				{	
					int since_usr_idx = i-1;
					last_follow.setLastuserId(ids.getIDs()[since_usr_idx]);
					page_no = (int)Math.ceil((since_usr_idx+1) / (ONE_PAGE_COUNT * 1.0));
					
					break;
				}
			}
		}
		
		Paging paging = new Paging();
		paging.setCount(ONE_PAGE_COUNT);
		paging.setPage(page_no);
		paging.setSinceId(last_follow.getLastUserId());

		List<User> followers = twitter.getFollowers(paging);
	
		for(int i=followers.size()-1;i>=0;i--)
		{
			User target_usr = followers.get(i);
			
			if(isFollow(target_usr) == false &&  follow_enable == true)
				twitter.createFriendship(target_usr.getScreenName());
			else if(isFollow(target_usr) == true && follow_enable == false)
				twitter.destroyFriendship(target_usr.getScreenName());
			else
				System.out.println("did not call a FriendshipMethod.");
		}
		
		updateLastFollowInfo(last_follow);
	}
	
	private boolean isFollow(User usr) throws TwitterException
	{
		return twitter.existsFriendship(twitter.getUserId(), usr.getScreenName());
	}
	
//	private void dispUserInfo(User usr) throws TwitterException
//	{
//		System.out.print("    ユーザー名:" + usr.getName());
//		System.out.print("    スクリーン名:" + usr.getScreenName());
//		System.out.print("    ユーザーID:" + Integer.toString(usr.getId()));
//		//System.out.print("    詳細分:" + usr.getDescription());
//		if(isFollow(usr) == true)
//			System.out.print("    フォロー済みユーザーです。");
//		else
//			System.out.print("    未フォローのユーザーです。");
//		System.out.println("");
//	}
}
